import re
import requests
import openpyxl


def get_weather():
    url = 'http://www.weather.com.cn/weather/101280601.shtml'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
    }

    resp = requests.get(url, headers=headers)
    resp.encoding = 'utf=8'

    pattern = r'<li>\s*<a href=".*?">\s*<span class="name">(\w+)</span>\s*<span class="weather">(\w+)</span>\s*<span class="wd">([0-9\/]+℃)</span>\s*<span class="zs">(\w+)</span>\s*</a>\s*</li>'
    matches = re.findall(pattern, resp.text)

    values = []
    for v in matches:
        values.append(list(v))

    return values


items = get_weather()


# 创建新的工作簿
workbook = openpyxl.Workbook()
# 创建新的工作对象
sheet = workbook.create_sheet('景区天气')
# 向工作表中添加数据
for v in items:
    # 一次添加一行数据
    sheet.append(v)
# 保存
workbook.save('data/景区天气.xlsx')
